package GUI;

import util.User;
import util.UserDAO;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.RoundRectangle2D;

/**
 * 登录界面
 */
public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private JLabel messageLabel;
    private JCheckBox rememberMeCheckBox;

    // 登录失败尝试次数
    private int loginAttempts = 0;
    private static final int MAX_LOGIN_ATTEMPTS = 3;

    public LoginFrame() {
        // 设置窗口标题和大小
        setTitle("绿色出行系统 - 登录");
        setSize(450, 420);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示
        setResizable(false);

        // 设置自定义内容面板（带渐变背景）
        setContentPane(new GradientPanel());
        getContentPane().setLayout(new BorderLayout());

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        titlePanel.setBorder(new EmptyBorder(30, 0, 20, 0));

        JLabel titleLabel = new JLabel("绿色出行倡导与数据记录系统", JLabel.CENTER);
        titleLabel.setFont(new Font("等线", Font.BOLD, 22));
        titleLabel.setForeground(new Color(0, 100, 0));
        titlePanel.add(titleLabel, BorderLayout.CENTER);

        getContentPane().add(titlePanel, BorderLayout.NORTH);

        // 创建登录面板
        JPanel loginPanel = new JPanel();
        loginPanel.setLayout(new GridBagLayout());
        loginPanel.setOpaque(false);
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(8, 15, 8, 15);

        // 创建用户名标签和文本框
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(new Font("等线", Font.BOLD, 15));
        usernameLabel.setForeground(new Color(50, 50, 50));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        loginPanel.add(usernameLabel, constraints);

        usernameField = new RoundedTextField(16);
        usernameField.setFont(new Font("等线", Font.PLAIN, 15));
        constraints.gridx = 1;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.WEST;
        loginPanel.add(usernameField, constraints);

        // 创建密码标签和密码框
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("等线", Font.BOLD, 15));
        passwordLabel.setForeground(new Color(50, 50, 50));
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.anchor = GridBagConstraints.EAST;
        loginPanel.add(passwordLabel, constraints);

        passwordField = new RoundedPasswordField(16);
        passwordField.setFont(new Font("等线", Font.PLAIN, 15));
        constraints.gridx = 1;
        constraints.gridy = 1;
        constraints.anchor = GridBagConstraints.WEST;
        loginPanel.add(passwordField, constraints);

        // 创建记住密码选项和找回密码链接的面板
        JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 80, 0));
        optionsPanel.setOpaque(false);

        // 添加记住密码选项
        rememberMeCheckBox = new JCheckBox("记住密码");
        rememberMeCheckBox.setFont(new Font("等线", Font.PLAIN, 13));
        rememberMeCheckBox.setOpaque(false);
        rememberMeCheckBox.setForeground(new Color(50, 50, 50));
        optionsPanel.add(rememberMeCheckBox);

        // 创建找回密码链接
        JLabel forgotPasswordLabel = new JLabel("<html><u>忘记密码?</u></html>");
        forgotPasswordLabel.setFont(new Font("等线", Font.PLAIN, 13));
        forgotPasswordLabel.setForeground(new Color(0, 102, 204));
        forgotPasswordLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        forgotPasswordLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                openForgotPasswordFrame();
            }
        });
        optionsPanel.add(forgotPasswordLabel);

        constraints.gridx = 1;
        constraints.gridy = 2;
        constraints.anchor = GridBagConstraints.WEST;
        loginPanel.add(optionsPanel, constraints);

        // 创建登录按钮
        loginButton = new GreenRoundedButton("登录");
        loginButton.setFont(new Font("等线", Font.BOLD, 15));
        loginButton.setPreferredSize(new Dimension(220, 40));
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                login();
            }
        });

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setOpaque(false);
        buttonPanel.add(loginButton);

        constraints.gridx = 0;
        constraints.gridy = 3;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.CENTER;
        constraints.insets = new Insets(20, 15, 8, 15);
        loginPanel.add(buttonPanel, constraints);

        // 创建注册链接
        JPanel registerPanel = new JPanel();
        registerPanel.setOpaque(false);
        JLabel registerPrompt = new JLabel("没有账号？");
        registerPrompt.setFont(new Font("等线", Font.PLAIN, 13));
        registerPanel.add(registerPrompt);

        JLabel registerLink = new JLabel("<html><u>立即注册</u></html>");
        registerLink.setFont(new Font("等线", Font.PLAIN, 13));
        registerLink.setForeground(new Color(0, 102, 204));
        registerLink.setCursor(new Cursor(Cursor.HAND_CURSOR));
        registerLink.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                openRegisterFrame();
            }
        });
        registerPanel.add(registerLink);

        constraints.gridx = 0;
        constraints.gridy = 4;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.CENTER;
        constraints.insets = new Insets(5, 15, 8, 15);
        loginPanel.add(registerPanel, constraints);

        // 创建消息标签
        messageLabel = new JLabel("", JLabel.CENTER);
        messageLabel.setFont(new Font("等线", Font.PLAIN, 13));
        messageLabel.setForeground(Color.RED);
        constraints.gridx = 0;
        constraints.gridy = 5;
        constraints.gridwidth = 2;
        constraints.insets = new Insets(8, 15, 8, 15);
        loginPanel.add(messageLabel, constraints);

        // 添加面板到窗口
        getContentPane().add(loginPanel, BorderLayout.CENTER);

        // 添加底部版权信息
        JLabel copyrightLabel = new JLabel("© 2025 绿色出行系统 版权所有", JLabel.CENTER);
        copyrightLabel.setFont(new Font("等线", Font.PLAIN, 12));
        copyrightLabel.setForeground(new Color(100, 100, 100));
        copyrightLabel.setBorder(new EmptyBorder(8, 0, 8, 0));
        getContentPane().add(copyrightLabel, BorderLayout.SOUTH);
    }

    /**
     * 处理登录逻辑
     */
    private void login() {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            messageLabel.setText("用户名和密码不能为空！");
            return;
        }

        if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
            messageLabel.setText("登录失败次数过多，请稍后再试！");
            loginButton.setEnabled(false);
            return;
        }

        UserDAO userDAO = new UserDAO();
        User user = userDAO.login(username, password);

        if (user != null) {
            // 登录成功，打开主界面
            MainFrame mainFrame = new MainFrame(user);
            mainFrame.setVisible(true);
            dispose(); // 关闭当前窗口
        } else {
            // 登录失败
            loginAttempts++;
            int remainingAttempts = MAX_LOGIN_ATTEMPTS - loginAttempts;

            if (remainingAttempts > 0) {
                messageLabel.setText("用户名或密码错误！剩余尝试次数：" + remainingAttempts);
            } else {
                messageLabel.setText("登录失败次数过多，请稍后再试！");
                loginButton.setEnabled(false);
            }
        }
    }

    /**
     * 打开注册界面
     */
    private void openRegisterFrame() {
        RegisterFrame registerFrame = new RegisterFrame(this);
        registerFrame.setVisible(true);
        setVisible(false); // 隐藏当前窗口
    }

    /**
     * 打开找回密码界面
     */
    private void openForgotPasswordFrame() {
        ForgotPasswordFrame forgotPasswordFrame = new ForgotPasswordFrame(this);
        forgotPasswordFrame.setVisible(true);
        setVisible(false); // 隐藏当前窗口
    }

    /**
     * 渐变背景面板
     */
    private class GradientPanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int w = getWidth();
            int h = getHeight();

            // 创建渐变颜色
            GradientPaint gradient = new GradientPaint(0, 0, new Color(230, 250, 230),
                    0, h, new Color(180, 230, 190));
            g2d.setPaint(gradient);
            g2d.fillRect(0, 0, w, h);

            // 添加装饰性元素 - 右下角圆形
            g2d.setColor(new Color(0, 100, 0, 15));
            for (int i = 0; i < 5; i++) {
                int size = 60 + i * 25;
                g2d.fillOval(w - size - 20, h - size - 20, size, size);
            }

            // 添加左上角装饰
            g2d.setColor(new Color(0, 100, 0, 12));
            for (int i = 0; i < 3; i++) {
                int size = 40 + i * 20;
                g2d.fillOval(20, 20, size, size);
            }

            // 添加中间淡淡的叶子图案
            g2d.setColor(new Color(0, 120, 0, 8));
            int leafSize = 180;
            g2d.fillOval(w / 2 - leafSize / 2, h / 2 - leafSize / 2 - 40, leafSize, leafSize);
        }
    }

    /**
     * 圆角文本框
     */
    private class RoundedTextField extends JTextField {
        public RoundedTextField(int columns) {
            super(columns);
            setOpaque(false);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(180, 180, 180)),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(255, 255, 255, 220));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
            super.paintComponent(g);
            g2.dispose();
        }
    }

    /**
     * 圆角密码框
     */
    private class RoundedPasswordField extends JPasswordField {
        public RoundedPasswordField(int columns) {
            super(columns);
            setOpaque(false);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(180, 180, 180)),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(255, 255, 255, 220));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
            super.paintComponent(g);
            g2.dispose();
        }
    }

    /**
     * 绿色圆角按钮
     */
    private class GreenRoundedButton extends JButton {
        public GreenRoundedButton(String text) {
            super(text);
            setOpaque(false);
            setFocusPainted(false);
            setBorderPainted(false);
            setContentAreaFilled(false);
            setForeground(Color.WHITE);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            if (getModel().isPressed()) {
                g2.setColor(new Color(0, 130, 0));
            } else if (getModel().isRollover()) {
                g2.setColor(new Color(0, 150, 0));
            } else {
                g2.setColor(new Color(0, 160, 0));
            }

            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 25, 25);

            // 添加高光效果
            if (!getModel().isPressed()) {
                g2.setPaint(new GradientPaint(0, 0, new Color(255, 255, 255, 100),
                        0, getHeight() / 2, new Color(255, 255, 255, 0)));
                g2.fillRoundRect(0, 0, getWidth(), getHeight() / 2, 25, 25);
            }

            g2.setColor(Color.WHITE);
            g2.setFont(getFont());
            FontMetrics fm = g2.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(getText())) / 2;
            int y = (getHeight() - fm.getHeight()) / 2 + fm.getAscent();
            g2.drawString(getText(), x, y);
            g2.dispose();
        }
    }
}